const GITHUB_URL="https://github.com";
const parseHtml = res => {
  var html = res.data;

  var start = html.indexOf("class=\"repo-list\"");
  var end = html.indexOf("class=\"px-3 d-block d-sm-none\"");
  html = html.substring(start - 4, end - 5);
  //抓取标题数组
  var titlelArr = html.match(/<a class=\"v-align-middle\"([\s\S]*?)<\/a>/g);
  if (null == titlelArr || titlelArr.length == 0) {
    return [];
  }
  var urlArr = [].concat(titlelArr);

  //处理标题数组
  titlelArr = titlelArr.map(function (item) {
    item = item.replace(/<\/?.+?>/g, "");
    return item;
  });


  //处理url地址数组
  var urlArr = urlArr.map(function (item) {
    var urlMatch = item.match(/href=\"([\s\S]*?)>/g);
    var url = urlMatch[0];
    url = url.replace("href=\"", "");
    url = url.replace("\">", "");
    return GITHUB_URL+url;
  });

  //抓取简介数组
  var summaryArr = html.match(/<p class=\"col-12 col-md-9 d-inline-block text-gray mb-2 pr-4\">([\s\S]*?)<\/p>/g);
  summaryArr = summaryArr.map(function (item) {
    item = item.replace(/<\/?.+?>/g, "");
    item = item.replace(/\s+/g, "");
    return item;
  });

  //抓取star数组 <div class=\"flex-shrink-0  <\/li>
  var starArr = html.match(/<div class=\"flex-shrink-0([\s\S]*?)<\/li>/g);
  starArr = starArr.map(function (item) {

    //如果不存在 点赞数
    if (item.indexOf("muted-link")<0)
    {
      return 0;
    }

    var starMatch = item.match(/<a class=\"muted-link\"([\s\S]*?)<\/a>/g);
    if (null == starMatch)
    {
      return 0;
    }

    var starHtml = starMatch[0];
    //去掉html
    starHtml = starHtml.replace(/<\/?.+?>/g, "");
    //去掉空格
    starHtml = starHtml.replace(/\s+/g, "");
    return starHtml;
  });


  //抓取更新时间数组<relative-time 
  var updatedArr = html.match(/<relative-time([\s\S]*?)<\/relative-time>/g);
  updatedArr = updatedArr.map(function (item) {
    //去掉html
    item = item.replace(/<\/?.+?>/g, "");
    return item;
  });

  var resultList = new Array();
  for (var i = 0; i < titlelArr.length; i++) {
    var project = {};
    project.headImg = [];
    project.title = titlelArr[i];
    project.summary = summaryArr[i];
    project.icon = "/static/icon/github.jpg";
    project.star = starArr[i];
    project.url=urlArr[i];
    project.updated = updatedArr[i];

    resultList.push(project);
  }
  return resultList;
}


//过滤出图片
const filterImg = html => {
  var imgArr = html.match(/<img src=\"([\s\S]*?)\"/g);
  if (null == imgArr) {
    return [];
  }
  imgArr = imgArr.map(function (item) {
    item = item.replace("<img src=\"", "");
    item = item.replace("\"", "");
    return item;
  });

  var imgArray = [];
  for (var i = 0; i < imgArr.length; i++) {

    if (imgArr[i].startsWith(GITHUB_URL)) {
      imgArray.push(imgArr[i]);
      continue;
    }

    if (imgArr[i].startsWith("/")) {
      imgArray.push(GITHUB_URL + imgArr[i]);
    }
  }
  return imgArray;
}

module.exports = {
  parseHtml: parseHtml,
  filterImg: filterImg
}